<template>
    <div>
        <el-dialog v-model="visible" :title="`${title}用户`" :close-on-click-modal="false" :close-on-press-escape="false"
            @close="close">
            <div v-loading="loading">
                <el-form ref="formRef" :model="formData" label-position="right" status-icon label-suffix=":"
                    label-width="80px" size="small">
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="用户昵称" prop="nickName"
                                :rules="[{ required: true, message: '请输入用户昵称', trigger: 'blur' }]">
                                <el-input v-model="formData.nickName" placeholder="请输入用户昵称" clearable
                                    show-word-limit></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="用户账号" prop="username"
                                :rules="[{ required: true, validator: usernameValidator, trigger: 'blur' }]">
                                <el-input v-model="formData.username" placeholder="请输入用户账号" clearable
                                    show-word-limit></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="手机号码" prop="mobile"
                                :rules="[{ required: true, validator: mobileValidator, trigger: 'blur' }]">
                                <el-input v-model="formData.mobile" placeholder="请输入手机号码" clearable
                                    show-word-limit></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="登录密码" prop="password"
                                :rules="[{ required: true, message: '请输入登录密码', trigger: 'blur' }]">
                                <el-input type="password" v-model="formData.password" placeholder="请输登录密码" clearable
                                    show-word-limit></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="分配角色" prop="roleIds">
                                <!-- 分配角色，使用下拉框选择 -->
                                 <el-select-v2
                                    v-model="formData.roleIds"
                                    :multiple="true"
                                    :options="roleOptions"
                                    :filterable="true"
                                    :clearable="true"
                                    :placeholder="'请选择角色'"
                                    ></el-select-v2>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="电子邮箱" prop="email">
                                <el-input v-model="formData.email" placeholder="电子邮箱" clearable
                                    show-word-limit></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="帐号锁定" prop="accountNonLocked"
                                :rules="[{ required: true, message: '请选择帐号锁定状态', trigger: 'change' }]">
                                <el-radio-group v-model="formData.accountNonLocked">
                                    <el-radio :value="true">未锁定</el-radio>
                                    <el-radio :value="false">已锁定</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="帐号过期" prop="accountNonExpired"
                                :rules="[{ required: true, message: '请选择', trigger: 'change' }]">
                                <el-radio-group v-model="formData.accountNonExpired">
                                    <el-radio :value="true">未过期</el-radio>
                                    <el-radio :value="false">已过期</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="密码过期" prop="credentialsNonExpired"
                                :rules="[{ required: true, message: '请选择', trigger: 'change' }]">
                                <el-radio-group v-model="formData.credentialsNonExpired">
                                    <el-radio :value="true">未过期</el-radio>
                                    <el-radio :value="false">已过期</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="备注信息" prop="remark">
                                <el-input v-model="formData.remark" type="textarea" placeholder="请输入内容" clearable
                                    show-word-limit></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row justify="center" class="mt10">
                        <el-button @click="close">取消</el-button>
                        <el-button type="primary" @click="submitForm">保存</el-button>
                    </el-row>
                </el-form>
            </div>
        </el-dialog>
    </div>
</template>

<script setup lang="ts" name="SystemUserEdit">
import useForm from '@/hooks/useForm';
import { ref, computed, watch } from 'vue'
import { add, update, checkExist } from '@/api/system/user'
import { getRoleList } from '@/api/system/role';
import { isMainAccount, isMobile } from '@/utils/validate';

// 定义自定义事件
const emit = defineEmits(['refresh'])
//初始化数据
const initData = { accountNonExpired: true, accountNonLocked: true, credentialsNonExpired: true }

const {
    formRef,
    title, type, visible, loading,
    formData, oldFormData,
    open,
    close,
    submitForm
} = useForm<SysUserType>({ initData, update, add }, emit)

defineExpose({
    open
})

// 校验用户帐号
const usernameValidator = async(rule: any, value: string, callback: Function) => {
    if (!value || value === '')
        return callback(new Error('用户帐号为必填项'))
    if (!isMainAccount(value)) {
        return callback(new Error('用户帐号只能是6-30字母、数字、下划线'))
    }
    if (oldFormData.value.username !== value) {
        const { data } = await checkExist({ username: value })
        if (data) return callback(new Error('用户帐号已经被注册，请更换一个'))
    }
    callback()
}
// 校验手机号
const mobileValidator = async (rule: any, value: string, callback: Function) => {
    if (!value || value === '') return callback(new Error('手机号必填'))
    if (!isMobile(value)) {
        return callback(new Error('手机号格式不正确'))
    }
    if (oldFormData.value.mobile !== value) {
        const {data} = await checkExist({mobile: value})
        if (data) return callback(new Error('手机号码已经被注册，请更换一个'))
    }
}

// 修改时，禁用密码输入框
const disabled = computed(() => type.value === 'edit')

// 角色选择下拉框
const roleOptions = ref([])
// 监听打开弹窗事件
watch(() => visible.value, (val) => {
    if (!val) return
    loadRoleOptions()
})
// 获取角色下拉框数据
async function loadRoleOptions() {
    try {
        loading.value = true
        const { data } = await getRoleList()
        if (data && data.length > 0) {
            roleOptions.value = data.map((item: any) => {
                return {
                    label: item.roleName,
                    value: item.id
                }
            })
        } else {
            roleOptions.value = []
        }
    } catch (error) {

    } finally {
        loading.value = false
    }
}
</script>

<style scoped></style>